import axios from 'axios';

export abstract class Watcher {
    watcherType: string;
    timer: any;
    onTime: (sender) => void;
    invealTiming: number;
    start() {
        this.timer = setInterval(() => {
            this.timeAction();
        }, this.invealTiming);
    }
    stop() {
        clearInterval(this.timer);
    }
    timeAction() {
        this.onTime(this);
    }
}



export class FBSWatcher extends Watcher {
    invealTiming = 20000;
    watcherType = "FBSWatcher";
}

export class CloundWatcher extends Watcher {
    invealTiming = 10000;
    watcherType = "CloundWatcher";
}


export abstract class Task {
    taskType: string;
    abstract selfCheck();
    destory() {

    }
    onChecked: (sender) => void
}

export class FBSLDCConfigTask extends Task {
    storeId;
    LDCHost;
    constructor(storeId, LDCHost) {
        super();
        this.storeId = storeId;
        this.LDCHost = LDCHost;
    }
    taskType = "FBSWatcher";
    async selfCheck() {
        try {
            await axios.get("http://" + this.LDCHost + "/api/system/isOnline");
            this.onChecked(true);
        } catch (error) {
            this.onChecked(false);
        }
    }
}

export class CloundLDCConfigTask extends Task {
    storeId;
    constructor(storeId) {
        super();
        this.storeId = storeId;
    }
    taskType = "CloundWatcher";
    async selfCheck() {
        try {
            const res = (await axios.get("/api/stores/" + this.storeId + "/config/get/config?type=system.ldc")).data;
            this.onChecked(res.data && res.data.value);
        } catch (error) {
            this.onChecked(null);
        }
    }
}


export class TaskManage {
    static current = new TaskManage();
    watcherList: Array<Watcher> = [];
    taskList: Array<Task> = [];
    addTask(task: Task) {
        this.taskList.push(task);
        this.watcherList.filter(watcher => watcher.watcherType == task.taskType).forEach(watcher => watcher.onTime = (sender) => {
            this.taskList.filter(task => task.taskType == sender.watcherType).forEach(task => task.selfCheck())
        })
    }
    public addWatcher(watcher: Watcher) {
        watcher.onTime = (sender: Watcher) => {
            this.taskList.filter(task => task.taskType == sender.watcherType).forEach(task => task.selfCheck())
        }
        this.watcherList.push(watcher);
    }
}
